import {useLocation} from 'react-router-dom';
import {Toast} from "antd-mobile";
import Props from "./Props";
import api from "./api";

let count:number = 0;
let handle:number;

const http = {
  hiddenLoading():void{
    if(count <= 0){
      clearTimeout(handle);
      Toast.hide();
    }
  },
  showLoading():void{
    count++;
    if(count === 1){
      console.log('loading-count',count);
      handle = window.setTimeout(()=>{
        Toast.loading('loading',0)
      },1000)
    }
  },
  stringify(data?:Props):string{
    if(!data) return '';
    const esc:Function = window.encodeURIComponent;
    const key = Object.keys(data);
    return key.map((k: string) => esc(k) + '=' + esc(data[k])).join('&');
  },
  useQuery():URLSearchParams{
    return new URLSearchParams(useLocation().search);
  },
  checkStatus(res:Response):Response{
    if(res.ok) return res;
    count = 0;
    this.hiddenLoading();
    Toast.fail('请求错误');
    throw new Error('err');
  },
  async _request(url:string,config?:RequestInit):Promise<Response>{
    try {
      this.showLoading();
      const res:Response = await fetch(api.proxy+url,config);
      const result:Response = await this.checkStatus(res).json();
      count--;
      this.hiddenLoading();
      return result;
    }catch (e) {
      console.dir(e);
      count = 0;
      this.hiddenLoading();
      Toast.fail('网络错误');
      throw e;
    }
  },
  async _get(url:string,data?:Props):Promise<Response>{
    const query:string = this.stringify(data);
    const s:string = url.includes('?')?'&':'?';
    return await this._request(url+s+query);
  },
  async _post(url:string,data?:Props):Promise<Response>{
    return await this._request(url,{
      method:'POST',body:this.stringify(data),
      headers:{'Content-Type':'application/x-www-form-urlencoded'}
    })
  },
  async _post_json(url:string,data?:Props):Promise<Response>{
    return await this._request(url,{
      method:'POST',body:JSON.stringify(data),
      headers:{'Content-Type':'application/json'}
    })
  }
};

export default http;
